import logging
import asyncio
import os

from pyppeteer import launch

from src.common.mem_data import MemData
from src.common.prj_path import get_abs_path
from src.common.utils import input_time_random, write_file, read_file

LOG = logging.getLogger()


class AutoLogin(object):
    def __init__(self):
        self.page = MemData.page
        self.user = MemData.config['account']['user']
        self.password = MemData.config['account']['password']
        self.cookie_path = get_abs_path('privacy', 'cookie.txt')

    async def if_have_cookie(self):
        try:
            cookie = read_file(self.cookie_path, json_flag=True)
            if not cookie or not isinstance(cookie,list):
                return False
            for item in cookie:
                await self.page.setCookie(item)
            return True
        except Exception as e:
            LOG.warning('read cookie, error={}'.format(e))

    async def auto_login(self):
        await self.page.type('input#fm-login-id.fm-text', self.user, {'delay': input_time_random()})
        await asyncio.sleep(1)
        await self.page.type('input#fm-login-password.fm-text', self.password, {'delay': input_time_random()})
        await asyncio.sleep(1)

    async def check_slider(self):
        slider = self.page.J('#span.nc-lang-cnt')
        if slider:
            LOG.info('slider is exsit')

    # async def try_validation(page):
    #     async def get_xy(start_x, start_y, length=300):
    #         points_x = [slide_speed_func(i / 30.0) for i in range(30)]
    #         A = 1.0 * length / points_x[-1]
    #         points_x = [A * i for i in points_x]
    #         print(points_x)
    #         for i in range(30):
    #             await page.mouse.move(start_x + points_x[i], start_y + (random.random() - 0.5))
    #             await page.waitFor(30)
    #
    #     btn_position = await page.evaluate('''
    #        () =>{
    #         return {
    #          x: document.querySelector('#nc_1_n1z').getBoundingClientRect().x,
    #          y: document.querySelector('#nc_1_n1z').getBoundingClientRect().y,
    #          width: document.querySelector('#nc_1_n1z').getBoundingClientRect().width,
    #          height: document.querySelector('#nc_1_n1z').getBoundingClientRect().height
    #          }}
    #         ''')
    #     x = btn_position['x'] + btn_position['width'] / 2
    #     y = btn_position['y'] + btn_position['height'] / 2
    #     await page.mouse.move(x, y)
    #     await page.mouse.down()
    #     await get_xy(x, y, 300)
    #     await page.mouse.up()

    async def click_login(self):
        # //*[@id="login-form"]/div[4]/button
        await self.page.keyboard.press('Enter')
        await asyncio.sleep(10)
        LOG.info("press enter")
        # await self.page.evaluate('''document.getElementById("J_SubmitStatic").click()''')

    async def get_cookies(self):
        cookies_list = await self.page.cookies()

        write_file(self.cookie_path, cookies_list, json_flag=True)
        LOG.info('write cookie success ,path={}'.format(self.cookie_path))

    async def run(self):
        if not await self.if_have_cookie():
            await self.auto_login()
            # await self.check_slider()
            await self.click_login()
            await self.get_cookies()
        else:
            LOG.info('have cookie, skip login')
